<template>
  <div class="leftmenu">
    <div class="top-menulist">
		<el-scrollbar style="height:calc(100% - 5px);width: 100%;">
			<div class="elmenubox">
				<el-menu default-active="1-3" class="el-menu-vertical-demo"  :collapse="isCollapse" @select="handleSelect">
					<!-- <el-menu-item index="7">
						<img :src="'/leftmenu/' + imgurl" alt="" class="menu-imgimg">
						<span>基本信息</span>
					</el-menu-item> -->
					<el-sub-menu :index="item.id" v-for="(item) in menuList" :key="item.id">
							<template #title>
								<img :src="'/leftmenu/' + item.weixuan" alt="" class="menu-imgimg">
								<span>{{item.name}}</span>
							</template>
							<el-menu-item-group v-for="t in item.children" :key="t.id">
								<el-menu-item :index="t.id"><i class="item_i">●</i>{{t.name}}</el-menu-item>
							</el-menu-item-group>
					</el-sub-menu>
				</el-menu>
			</div>
	  </el-scrollbar>
	  </div>
	  
  </div>
</template>

<script>
import {restartSystem,pingSystem} from "../../../api/forwardApi";
import {ProjectImport} from "../../../api/Interface";
export default {
  data() {
	return {
		isMask2:false,
		dialogVisible:false,
		imgurl:"caobiao.png",
		isCollapse:false,
		daorudiofalse:false,
		isMask:false,
	    nowLeftMenu:1,
	
	   //通用纯净版 menuListPurity
	   menuList:[
			
		   {
			   name:"工程配置",
			   id:"1",
			   webPackUrl:'collectionChannel',
			   weixuan:('yuce.png'),
			   children:[

				{
				  name:"设备信息",
				  id:"1-3",
				  webPackUrl:'deviceEditing',
				  weixuan:('wangguan.png'),
			    },
			   ]
		   },

		   
	   ],
	  
	   isShensuo:false,
	   pathUrl:""

	};
  },

  mounted() {
	//   console.log("触发");
      var path = window.location.origin;
      this.pathUrl = path
  },
  computed:{
     preventRouter() {//阻止路由
			return 1;
			// return this.$store.menuStore.state.preventRouter;
		}
    
   
  },
	watch: {
         preventRouter(){
			 this.nowLeftMenu = 11
		 },
	},

  methods: {
	//切换路由
	handleSelect(val,eee){
	   if(val == 7){
		 var webPack = `/gatewayInfo`
		 this.$router.push(webPack)
		 return
	   }
	   var myurl = window.location.host.split(':')[0];//页面路径
	   var finArr = this.menuList.filter(item => item.id == eee[0])
	   var pastArr = finArr[0].children.filter(item => item.id == val)
	   var row = pastArr[0]
	   if(row.id == '10001000'){
            this.Restartfn()
			return
	   }
	   if(row.webPackUrl.includes('subApp/') || row.webPackUrl == '/chart/home'){
             const base_url = `http://${myurl}:19003`
             const params = {
                  token: localStorage.getItem('token')
             };
            const query_string = new URLSearchParams(params).toString();
            const url = `${base_url}#/${row.webPackUrl}?${query_string}`;
            window.open(url, '_blank');
        }
		this.nowLeftMenu = row.id
		// console.log("切换",row);
		if(row.name == '数据备份'){
			this.dialogVisible = true
			return
		}
		var webPack = `/${row.webPackUrl}`
		this.$router.push(webPack)
	},
 	//切换路由
	 menu_fn(row){
		
		if(row.id == '10001000'){
            this.Restartfn()
			return
		}
		if(row.isTitle){
		   return
	    }
		this.activeIndex = ""
		this.nowLeftMenu = row.id
		// console.log("row.webPackUrl",row.webPackUrl);
		 if(row.webPackUrl.includes('subApp/') || row.webPackUrl == '/chart/home'){
             const base_url = DWSystemSetting.qiankunURL;
             const params = {
                  token: localStorage.getItem('token')
             };
            const query_string = new URLSearchParams(params).toString();
            const url = `${base_url}#${row.webPackUrl}?${query_string}`;
            window.open(url, '_blank');
        }
		if(row.name == '数据备份'){
			this.dialogVisible = true
			return
		}
		var webPack = `/${row.webPackUrl}`
		this.$router.push(webPack)
		
		  
	 },
	 //重启网关
	 Restartfn(){
		 this.$confirm(`是否要重新启动吗？`,'提示',{
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
				//   this.$message({showClose: true,message: '删除成功',type: 'success'});
				//    this.$message.error('删除失败！！')
				 this.isMask = true
				//  融合版为1，纯净版为2
				restartSystem({'model':2}).then(res => {})
				setTimeout(() => {
					this.viewChongqi()
				},10000)
				
                   
            }).catch(() => {
              // ...
            });
	 },
	 //检查管理机是否重启完成
	 viewChongqi(){
		pingSystem().then(res => {
			// console.log("检查管理机心跳",res);
			if(res.code == 200){
				 this.isMask = false
				 this.$message({showClose: true,message: '重启成功',type: 'success'});
				//   window.location.reload();
			}else {
				setTimeout(() => {
					this.viewChongqi()
			 	},2000)
			}
		}).catch(() => {
			 setTimeout(() => {
				 this.viewChongqi()
			 },2000)
		})
	 },
	 fugaifn(){
        this.daorudiofalse = false
		this.dialogVisible = false
        this.isMask = true
        //  融合版为1，纯净版为2
        restartSystem({'model':2}).then(res => {})
				setTimeout(() => {
					this.viewChongqi()
				},10000)
    },
	 handleFileChange(event){
      const files = event.target.files;
      let formData = new FormData()
      formData.append('file', files[0]);
        this.isMask2 = true
      ProjectImport(formData).then(res => {
        //  console.log("导入工程",res);
          if(res != undefined){
            this.isMask2 = false
            this.daorudiofalse = true
          }else {
            this.isMask2 = false
            this.$message.error('导入工程失败')
          }
      })
      
    },
	importExportfn(type){
      //  this.nowOperatingDevice = type
      //  this.importExport = true
      if(type == '导入'){
         this.$refs.dianfileInput.click();
      }else {
        this.isMask2 = true
        this.downloadDbFile('/Project/Export');
       
      }
    },
	async  downloadDbFile(url) {
  try {
    // 1. 发起请求，获取二进制数据
    const response = await fetch(url,{
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json', // 根据后端要求调整
      },
    });
    
    if (!response.ok) {
      throw new Error(`请求失败: HTTP ${response.status}`);
    }
    // console.log("导出",response);

    // 2. 获取 Blob 数据（MIME 类型为 application/x-sqlite3）
    const blob = await response.blob();

    // 3. 创建临时下载链接
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = 'webserver.db'; // 设置文件名
    document.body.appendChild(link);

    // 4. 触发下载
    link.click();
    this.isMask2 = false

    // 5. 清理临时对象
    setTimeout(() => {
      window.URL.revokeObjectURL(downloadUrl);
      document.body.removeChild(link);
    }, 100);
  } catch (error) {
    this.$message.error('导出工程失败')
	this.isMask2 = false
    // console.error('下载失败:', error);
    // alert('文件下载失败，请重试或联系管理员');
  }
   },
    
  },
};
</script>
<style scoped lang="scss">
   .leftmenu {
	  width: 180px;
		height: 100%;
		// padding: 12px;
		box-sizing: border-box;
		background-color: #25282c;
		transition: 0.3s;
		.juli {
			 display: flex;
			 align-items: center;
			 justify-content: center;
			 margin-top: 20px;
		}
		.daorubtn {
                 width: 140px;
                 height: 50px;
                 border: 1px solid #D8D8D8;
                 box-sizing: border-box;
                 border-radius: 4px;
                 overflow: hidden;
                 font-size: 18px;
                 display: flex;
                 align-items: center;
                 justify-content: center;
                 color:#1A1A1A;
                 margin-bottom: 12px;
				 cursor: pointer;
                 &.active {
                   background-color: #3C89F2;
                   border-color: #3C89F2;
                   color: #fff;
                 }
               }
		.elmenubox {
			 width: 180px;
			 height: 100%;
			 padding: 12px;
			 box-sizing: border-box;
		}
		:deep(.el-menu-item) {
			 height: 36px;
			 line-height: 36px;
			 border-radius: 4px;
			 span {
				 color: #cccccc;
				 font-size: 13px;
				 line-height: 17px;
			 }
		}
		:deep(.el-sub-menu .el-sub-menu__title:hover) {
			 background-color: #31363E !important;
		}
		.menu-imgimg {
			 width: 20px;
			 height: 20px;
			 margin-right: 6px;
		}
		:deep(.el-sub-menu__icon-arrow) {
			 right: 8px;
			 color: #909399;
		}
	    :deep(.el-sub-menu .el-menu-item) {
			  height: 36px;
			 line-height: 36px;
			 padding: 0px;
			 padding-left: 40px !important;
   			 min-width: 100px;
			 margin: 0px;
			 width: 100%;
			 box-sizing: border-box;
			 display: flex;
   			 align-items: center;
			 color: #CCC !important;
			 font-size: 0.13rem;
			 i {
				 margin-right: 4px;
				 color: #909399;
			 }
		}
		:deep(.el-menu-item.is-active) {
				background-color: #2178F1 !important;
				color: #fff !important;
				span {
					 color: #fff !important;
				}
		}
		:deep(.el-menu-item-group) {
			 margin-bottom: 5px;
		}
		:deep(.el-menu-item-group__title) {
			 padding: 0px;
		}
		:deep(.el-sub-menu__title) {
			 height: 36px;
			 line-height: 36px;
			 padding: 0px;
			 padding-left: 12px !important;
			 margin-bottom: 10px;
			 span {
				 color: #cccccc;
				 font-size: 13px;
				 line-height: 17px;
			 }
		}
		&.leftmenu-active {
			 min-width: 72px;
			 .menu-item {
				 padding-left: 0px !important;
				 display: flex;
				 justify-content: center;
				 .menu-img {
					 margin-right: 0px !important;
				 }
			 }
		}
		.top-menulist {
			 width: 100%;
			 height: 100%;
		}
		.menu-item {
			 width: 100%;
			 height: 36px;
			 display: flex;
			 align-items: center;
			 margin-bottom: 10px;
			 color: #cccccc;
			 font-size: 13px;
			 border-radius: 4px;
			 padding-left: 12px;
			 box-sizing: border-box;
       cursor: pointer;
			 .menu-img {
				margin-right: 8px;
				width: 20px;
				height: 20px;
				img {
					 width: 20px;
			    	height: 20px;
				}
			 }
			 &:hover {
				 background-color: #31363E;
			 }
			 &.menu-item-active {
				  background-color: #2178F1;
				  color: #fff;
				  
			 }
			 .menuname {
				 font-size: 13px;
			 }
			 
		}
    .menunameline {
				  width: 100%;
				  height: 1px;
				  background-color: #2F323D;
			 }
		.bottom-shensuo {
			   width: 100%;
			   height: 32px;
			//    background-color: red;
			   border-top: 1px solid #2F323D;
			   display: flex;
			   justify-content: center;
			   img {
				margin-top: 12px;
				cursor: pointer;
			   }
		}
    .chongqiwangguan {
       width: 100%;
       height: 44px;
       display: flex;
       align-items: center;
       color: #cccccc;
       padding-left: 12px;
       box-sizing: border-box;
	   cursor: pointer;
       span {
        margin-left: 8px;
        font-size: 13px;
       }

    }
   }
</style>